// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Async event handler - message queue between clients & server
// -----------------------------------------------

private ["_variable","_variablename"];

wcqueue = [];

WC_fnc_publicvariable = {
	private ["_variablename","_variablevalue","_type","_playerid"];

	_variablename = _this select 0;
	_type         = _this select 1;
	_playerid     = _this select 2;

	_variablevalue = call compile format ["%1", _variablename];
	wcaddqueue = [_variablename, _variablevalue, _type];

	if (isServer and local player) then {
		wcqueue = wcqueue + [wcaddqueue];
	};

	switch (toLower _type) do {
		case "server": {
			publicVariableServer "wcaddqueue";
		};

		case "client": {
			if (!isNil "_playerid") then {
				_playerid publicVariableClient "wcaddqueue";
			} else {
				publicVariable "wcaddqueue";
			};
		};

		default {
			publicVariable "wcaddqueue";
		};
	};
};

"wcaddqueue" addPublicVariableEventHandler {
	// Insert message in the queue if its for server or everybody
	if (isServer) then {
		if (((wcaddqueue select 2) == "server") or ((wcaddqueue select 2) == "all")) then {
			wcqueue = wcqueue + [wcaddqueue];
		};
	};

	// Insert message in the queue if its for client or everybody
	if (local player) then {
		if (((wcaddqueue select 2) == "client") or ((wcaddqueue select 2) == "all")) then {
			wcqueue = wcqueue + [wcaddqueue];
		};
	};
};

while {true} do {
	waitUntil {count wcqueue > 0};

	_variablename = (wcqueue select 0) select 0;
	_variable     = (wcqueue select 0) select 1;

	if (isServer) then {
		call compile format ["wcgarbage = [%1] spawn WC_fnc_netcode_server_%2;", _variable, _variablename];
	};

	if (local player) then {
		call compile format ["wcgarbage = [%1] spawn WC_fnc_netcode_%2;", _variable, _variablename];
	};

	wcqueue set [0, -1]; 
	wcqueue = wcqueue - [-1];

	sleep 0.1;
};